package com.zsxb.crm.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zsxb.crm.context.BaseContext;
import com.zsxb.crm.context.StatusContext;
import com.zsxb.crm.dto.*;
import com.zsxb.crm.enumeration.ResultCodeEnum;
import com.zsxb.crm.exception.BaseException;
import com.zsxb.crm.mapper.*;
import com.zsxb.crm.pojo.Clue;
import com.zsxb.crm.pojo.Record;
import com.zsxb.crm.pojo.SysStatus;
import com.zsxb.crm.result.PageResult;
import com.zsxb.crm.service.ClueService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author ljk74
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {
    private final ClueMapper clueMapper;
    private final RecordMapper recordMapper;
    private final SysStatusMapper sysStatusMapper;
    private final ActivityMapper activityMapper;
    private final UserMapper userMapper;

    @Override
    public PageResult pageQuery(ClueSearchDto clueSearchDto) {
        PageHelper.startPage(clueSearchDto.getPageNum(), clueSearchDto.getPageSize());
        if (clueSearchDto.getParams() != null) {
            String beginCreateTime = clueSearchDto.getParams().get("beginCreateTime").toString();
            String endCreateTime = clueSearchDto.getParams().get("endCreateTime").toString();
            clueSearchDto.setBeginCreateTime(beginCreateTime);
            clueSearchDto.setEndCreateTime(endCreateTime);
        }
        log.info("状态：{}", clueSearchDto.getStatus());
        //PageHelper.startPage(clueSearchDto.getPageNum(),clueSearchDto.getPageSize());
        List<Clue> list = clueMapper.selectByCondition(clueSearchDto);
        Page<Clue> p = (Page<Clue>) list;
        return new PageResult(p.getTotal(), p.getResult(), null);
    }

    @Override
    public PageResult poolPageQuery(ClueSearchDto clueSearchDto) {
        PageHelper.startPage(clueSearchDto.getPageNum(), clueSearchDto.getPageSize());
        if (clueSearchDto.getParams() != null) {
            String beginCreateTime = clueSearchDto.getParams().get("beginCreateTime").toString();
            String endCreateTime = clueSearchDto.getParams().get("endCreateTime").toString();
            clueSearchDto.setBeginCreateTime(beginCreateTime);
            clueSearchDto.setEndCreateTime(endCreateTime);
        }
        clueSearchDto.setStatus(StatusContext.KICK_OUT);
        List<Clue> list = clueMapper.selectByCondition(clueSearchDto);
        Page<Clue> p = (Page<Clue>) list;
        return new PageResult(p.getTotal(), p.getResult(), null);
    }

    @Override
    public PageResult findRecordByClueId(Long clueId) {
        PageHelper.startPage(1, 10);
        List<Record> list = recordMapper.findByClueId(clueId);
        Page<Record> p = (Page<Record>) list;
        return new PageResult(p.getTotal(), p.getResult(), null);
    }

    @Override
    @Transactional
    public void backCluePool(Long clueId, ClueRecrodDTO clueRecrodDTO) {
        Clue clue = clueMapper.selectById(clueId);
        if (clue == null) {
            throw new BaseException(ResultCodeEnum.THE_DATA_DOES_NOT_EXIST);
        }
        clue.setStatus(StatusContext.KICK_OUT.toString());
        List<SysStatus> byDictType = sysStatusMapper.findByDictType(StatusContext.REASONS_FOR_REPORTING);
        SysStatus sysStatus = byDictType.stream().filter(o -> o.getDictValue().equals(clueRecrodDTO.getReason())).findFirst().orElse(new SysStatus());
        clue.setOwner(null);
        clue.setOwnerTime(null);
        clue.setFalseCount(clue.getFalseCount() + 1);
        if (clue.getFalseCount() > 3) {
            clueMapper.deleteById(clueId);
            return;
        }
        clue.setRemark(clueRecrodDTO.getRemark());
        clue.setBackReason(sysStatus.getDictLabel());
        clueMapper.backCluePool(clue);
    }

    @Override
    public void assign(ClueGainDTO clueGainDTO) {
        List<Clue> list = clueMapper.selectByClueIds(clueGainDTO.getIds());
        Integer userCount = clueMapper.countWithUserId(clueGainDTO.getUserId());
        if (userCount+clueGainDTO.getIds().size()>20){
            throw new BaseException(ResultCodeEnum.CLUE_HAD_COUNT);
        }
        String username = userMapper.findUserNameById(clueGainDTO.getUserId());
        for (Clue clue : list) {
            clue.setOwner(username);
            clue.setStatus(StatusContext.TO_BE_FOLLOWED_UP.toString());
            clue.setOwnerTime(LocalDateTime.now());
            clueMapper.updateById(clue);
        }
    }

    @Override
    @Transactional
    public void addClueDetail(ClueDTO clueDTO) {
        Clue clue = clueMapper.selectById(clueDTO.getClueId());
        BeanUtils.copyProperties(clueDTO,clue);
        Record record = new Record();
        BeanUtils.copyProperties(clueDTO,record);
        clue.setLevel(clueDTO.getLevel());
        clue.setId(Long.valueOf(clueDTO.getClueId()));
        clue.setStatus(StatusContext.FOLLOW_UP.toString());
        clueMapper.updateById(clue);
        recordMapper.insert(record);
    }

    @Override
    public Clue getByClueId(Long clueId) {
        log.info("查询线索参数:{}", clueId);
        return clueMapper.getByClueId(clueId);
    }

    @Override
    public void gain(ClueGainDTO clueGainDTO) {
        clueMapper.gain(clueGainDTO);
    }

    @Override
    @Transactional
    public void add(AddClueDTO dto) {
        List<Clue> list = clueMapper.findAll();
        String clue1 = list.stream().map(Clue::getPhone).filter(Objects::nonNull).filter(o -> o.equals(dto.getPhone())).findFirst().orElse(null);
        String clue2 = list.stream().map(Clue::getWeixin).filter(Objects::nonNull).filter(o -> o.equals(dto.getWeixin())).findFirst().orElse(null);
        String clue3 = list.stream().map(Clue::getQq).filter(Objects::nonNull).filter(o -> o.equals(dto.getQq())).findFirst().orElse(null);
        log.info("数据检查：{}|{}|{}", clue1, clue2, clue3);
        if (clue1 != null || clue2 != null || clue3 != null) {
            throw new BaseException(ResultCodeEnum.THE_DATA_ALREADY_EXISTS);
        }
        Clue clue = new Clue();
        BeanUtils.copyProperties(dto, clue);
        clue.setStatus(StatusContext.TO_BE_FOLLOWED_UP.toString());
        clue.setOwner(BaseContext.getCurrentId());
        clue.setOwnerTime(LocalDateTime.now());
        clue.setActivityId(dto.getActivityId());
        String name = activityMapper.findNameById(dto.getActivityId());
        clue.setActivityName(name);
        clue.setFalseCount(StatusContext.FALSE_COUNT);
        clueMapper.add(clue);
    }

}
